package com.none.staff.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Environment;
import android.util.Base64;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by peter on 2017/9/27.
 */

public class ImageProcessingUtil {
    private static ImageProcessingUtil imageProcessingUtil;

    private ImageProcessingUtil() {

    }

    public static ImageProcessingUtil getInstances() {
        synchronized (ImageProcessingUtil.class) {
            if (imageProcessingUtil == null) {
                imageProcessingUtil = new ImageProcessingUtil();
            }
            return imageProcessingUtil;
        }
    }

    /**
     * bitmap转为base64
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 将图片保存到本地文件
     *
     * @param bitmap
     * @param fileName
     * @throws IOException
     */
    public void saveBitmap(Bitmap bitmap, String fileName) throws IOException {
//        File file = new File(this.getFilesDir() + "/" + fileName);
        File file = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
                out.flush();

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据相机实时预览的数据，获取到bitmap
     *
     * @param data
     * @param _camera
     * @return
     */
    public Bitmap decodeToBitMap(byte[] data, Camera _camera) {
        Camera.Size size = _camera.getParameters().getPreviewSize();
        try {
            YuvImage image = new YuvImage(data, ImageFormat.NV21, size.width,
                    size.height, null);
            if (image != null) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                image.compressToJpeg(new Rect(0, 0, size.width, size.height),
                        100, stream);
                Bitmap bmp = BitmapFactory.decodeByteArray(
                        stream.toByteArray(), 0, stream.size());
                stream.close();
                return bmp;
            }
        } catch (Exception ex) {
        }
        return null;
    }

    public void scaleImage(int screenWidth, int screenHeight, ImageView image) {
        // 拿到图片的宽和高
        int drawableW = image.getWidth();
        int drawableH = image.getHeight();
        float scale = 1.0f;
        int frameSize = screenWidth - 80 * 2;

        // 大图
        if (drawableW > frameSize && drawableH < frameSize) {
            scale = 1.0f * frameSize / drawableH;
        } else if (drawableH > frameSize && drawableW < frameSize) {
            scale = 1.0f * frameSize / drawableW;
        } else if (drawableW > frameSize && drawableH > frameSize) {
            float scaleW = frameSize * 1.0f / drawableW;
            float scaleH = frameSize * 1.0f / drawableH;
            scale = Math.max(scaleW, scaleH);
        }

        // 太小的图片放大处�?
        if (drawableW < frameSize && drawableH > frameSize) {
            scale = 1.0f * frameSize / drawableW;
        } else if (drawableH < frameSize && drawableW > frameSize) {
            scale = 1.0f * frameSize / drawableH;
        } else if (drawableW < frameSize && drawableH < frameSize) {
            float scaleW = 1.0f * frameSize / drawableW;
            float scaleH = 1.0f * frameSize / drawableH;
            scale = Math.max(scaleW, scaleH);
        }
        android.graphics.Matrix mScaleMatrix = new android.graphics.Matrix();
        mScaleMatrix.postTranslate((screenWidth - drawableW) / 2,
                (screenHeight - drawableH) / 2);
        mScaleMatrix.postScale(scale, scale, screenWidth / 2,
                screenHeight / 2);
        // 图片移动至屏幕中�?
//        image.setImageMatrix(mScaleMatrix);
    }

    /**
     * 压缩图片大小的方法
     */
    public Bitmap zoomBitmap(Bitmap bitmap) {
        Bitmap result;
        Matrix matrix = new Matrix();
        matrix.reset();
        // 此处自己添加方法对图片进行大小
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        // float zoom = (float)Math.sqrt(20 * 1024 /
        // (float)out.toByteArray().length);
        // matrix.setScale(0.9f, 0.9f);
        result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        out.reset();
        result.compress(Bitmap.CompressFormat.JPEG, 100, out);
        while (out.toByteArray().length > 20 * 1024) {
            System.out.println(out.toByteArray().length);
            matrix.setScale(0.9f, 0.9f);
            result = Bitmap.createBitmap(result, 0, 0, result.getWidth(),
                    result.getHeight(), matrix, true);
            out.reset();
            result.compress(Bitmap.CompressFormat.JPEG, 70, out);
        }
        return result;
    }


    public Bitmap base64ToBitmap(String string) {
        //将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
